class Solution {
public:
    int trap(vector<int>& height) {
       vector<int> v1;
       int ans = 0;
       int n = height.size();
       for(int i = 0;i<n;i++)
       {
            while(!v1.empty() && height[v1.back()] < height[i])
            {
                int temp = v1.back();
                v1.pop_back();
                if(v1.empty())
                {
                    break;
                }
                int h = min(height[i]-height[temp],height[v1.back()]-height[temp]);
                int l = i-v1.back()-1;
                ans += h*l;
            }
            v1.push_back(i);
       }
      return ans;
    }
};